<?php

namespace App\Logics;


use App\Models\Order;
use App\Models\SiteConfig;
use App\Service\Base\Logic;
use App\Service\WeChat\MiniPayV2;

class MiniPayLogicV2 extends Logic
{

    // 下单 并 支付
    public function makeOrderPay($myUid)
    {
        $opt       = $this->option();
        $event_id  = $opt->getData('event_id', 0, 'intval');
        $share_uid = $opt->getData('share_uid', 0, 'intval');
        $users     = $opt->getData('users', [], 'is_array');  // 报名用户列表
        $money     = $opt->getData('money', 0, 'floatval');
        $openid    = $opt->getData('openid', null, 'trim');

        // 查询 配置信息
        $config = $this->getConfig();
        if($config === false){
            return $this->_returnFail($this->error);
        }

        // 执行下单
        $orderDb = new Order();
        $result  = $orderDb->makeOrder($myUid, $event_id, $users, $share_uid, $money);
        if($result === false){
            return $this->_returnFail($orderDb->getError());
        }

        // 判断支付金额
        $_money  = $result['money'];
        $orderNo = $result['order_no'];
        $body    = '报名参加活动';
        if($_money != $money){
            return $this->_returnFail('支付金额错误！');
        }


        $payV2  = new MiniPayV2($config['wx_mini_appid'], $config['wx_mini_key'], $config['wx_mini_mchid']);
        $notify = $_SERVER['SERVER_NAME'].'/mobile/pay/notify_wx_mini';
        $param  = $payV2->wxMiniPay($orderNo, $openid, $money, $body, $notify);

        return $param;
    }


    // 支付：已经下单，继续支付
    public function makePay()
    {
        $opt     = $this->option();
        $money   = $opt->getData('money', 0, 'intval');
        $openid  = $opt->getData('openid', null, 'trim');
        $orderNo = $opt->getData('order_no', null, 'trim');

        // 查询 配置信息
        $config = $this->getConfig();
        if($config === false){
            return $this->_returnFail($this->error);
        }


        $payV2  = new MiniPayV2($config['wx_mini_appid'], $config['wx_mini_key'], $config['wx_mini_mchid']);
        $notify = $_SERVER['SERVER_NAME'].'/mobile/pay/notify_wx_mini';
        $body   = '报名参加活动';
        $param  = $payV2->wxMiniPay($orderNo, $openid, $money, $body, $notify);


        return $param;
    }

    // 获取配置信息
    protected function getConfig()
    {
        $config = (new SiteConfig())->getConfig();
        $config = array_column($config, 'value', 'field');
        if(empty($config['wx_mini_appid']) || empty($config['wx_mini_key']) || empty($config['wx_mini_mchid']) || empty($config['serial_no'])){
            return $this->_returnFail('请配置微信小程序信息！');
        }

        return $config;
    }

}


